<html>
<head>
    <title></title>
    <link rel="shortcut icon" href="{{ .IconURL }}" type="image/x-icon">
</head>
<body style="margin: 0">
    <script type="text/javascript" src="/koko/static/js/jquery-3.3.1.js"></script>
    <script type="text/javascript" src="/koko/static/js/jquery-ui-1.12.1.js"></script>
    <script type="text/javascript" src="/koko/static/plugins/elfinder/elfinder.full.js"></script>
    <script type="text/javascript" src="/koko/static/plugins/elfinder/i18n/elfinder.pl.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="/koko/static/js/jquery-ui-1.12.1.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/koko/static/plugins/elfinder/css/elfinder.full.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/koko/static/plugins/elfinder/css/theme-gray.css">
    <script type="text/javascript" src="/koko/static/js/koko.js"></script>
    <script type="text/javascript" charset="utf-8">
        var urlParams = new URLSearchParams(window.location.search);
        var scheme = document.location.protocol == "https:" ? "wss" : "ws";
        var port = document.location.port ? ":" + document.location.port : "";
        var baseWsUrl = scheme + "://" + document.location.hostname + port + "/koko/ws/elfinder/?"
        var requireParams = new URLSearchParams();
        var targetId = {{ .ID }};
        requireParams.append('type', "elfinder");
        requireParams.append('target_id', targetId );
        var wsURL = baseWsUrl + requireParams.toString();
        let ws = new WebSocket(wsURL, ["JMS-KOKO"]);
        let interval;
        let wsId = '';
        ws.onopen =function (e) {
            if (interval != null){
                clearInterval(interval)
            }
            interval = setInterval(function () {
                if (ws.readyState === WebSocket.CLOSING ||
                    ws.readyState === WebSocket.CLOSED) {
                    clearInterval(interval)
                    return
                }
                ws.send(message(wsId,'PING', ""));
            }, 25 * 1000);
        }
        ws.onerror = function (e) {
            alert("Connection closed")
        }

        ws.onclose = function(e) {
            alert("Connection closed")
        }
        ws.onmessage = function(e) {
            let msg = JSON.parse(e.data)
            switch (msg.type) {
                case 'CONNECT':
                    wsId = msg.id
                    initElfinder(msg.id)
                    break
                case "CLOSE":
                    break
                case "PING":
                    break
                default:
                    console.log(msg)
            }
        }
        var toolbar =  [
            ['back', 'forward'],
            ['mkdir', 'mkfile'],
            ['copy', 'cut', 'paste'],
            ['rm'],
            ['rename'],
            ['view'],
        ];
        if (targetId === '_') {
            toolbar.push(['search'])
        }
        var url = '/koko/elfinder/connector/'+ targetId + '/';
        function initElfinder(sid) {
            var elf;
            var opts = {
	    		uiOptions : {
	    			toolbar: toolbar,
                    cwd : {oldSchool: true}
	    		},
                customData: {'sid': sid},
                customHeaders: {"JMS-KoKo-Request-ID": sid},
                width: '100%',
	    		url: url,
                resizable: false,
                lang: 'pl',
                requestType: 'get',
                contextmenu: {
                    navbar: [
                        'rm'
                    ],
                    cwd: [
                        'reload', 'back', 'up', '|', 'mkdir', 'mkfile', '|',
                        'upload', 'paste'
                    ],
                    files: [
                        'rm', 'rename', 'download', 'copy', 'cut', 'paste'
                    ]
                },
                rememberLastDir: false,
                placesFirst: false,
                reloadClearHistory: true
	    	};
	    	var start = function(lng) {
	    		$(function() {
	    			// Make elFinder (REQUIRED)
                    opts.lang = lng;
	    			elf = $('#elfinder').elfinder(opts).elfinder('instance');
                    $(window).trigger('resize');
	    		});
	    	};
	    	var getCookieByName = function (name) {
                var cookies = document.cookie.split("; ")
                for ( var i = 0; i < cookies.length; i++) {
                    var arr = cookies[i].split("=");
                    if (arr[0] === name){
                        return arr[1];
                    }
                }
                return "";
            }
	    	var load = function () {
                var loct = window.location.search;
		        var full_lng, locm, lng;
     		    if (loct && (locm = loct.match(/lang=([a-zA-Z_-]+)/))) {
          		    full_lng = locm[1];
          	    } else {
          	    	full_lng = (navigator.browserLanguage || navigator.language || navigator.userLanguage);
          	    }
          	    lng = full_lng.substr(0,2);
          	    if (lng === 'ja') {
                    lng = 'jp';
                }
          	    else if (lng === 'pt') {
          	        lng = 'pt_BR';
                }
          	    else if (lng === 'zh') {
          	        lng = (full_lng.substr(0,5) === 'zh-tw')? 'zh_TW' : 'zh_CN';
                }
                if (lng !== 'en') {
        		    $.ajax({
        		    	url : '/koko/static/plugins/elfinder/i18n'+'/elfinder.'+lng+'.js',
        		    	cache : true,
        		    	dataType : 'script'
        		    })
        		    .done(function() {
        		    	start(lng);
        		    })
        		    .fail(function() {
        		    	start('en');
        		    });
	           } else {
	           	    start(lng);
	           }
            };
	    	load();
            var kokoLang = getCookieByName("django_language");
            if ( kokoLang.startsWith("en")) {
                document.title = "File Manager"
            }else {
                document.title = "文件管理"
            }
            var resizeTimer;
            $(window).resize(function () {
                resizeTimer && clearTimeout(resizeTimer);
                if (!$('#elfinder').hasClass('elfinder-fullscreen')) {
                    resizeTimer = setTimeout(function () {
                        var h, w;
                        if (window !== parent) {
                            h = parseInt(parent.$('.window.active').height());
                            w = parseInt(parent.$('.window.active').width());
                        } else {
                            h = parseInt($(window).height());
                            w = parseInt($(window).width());
                        }
                        var ori_h = parseInt($('#elfinder').height());
                        var ori_w = parseInt($('#elfinder').width());
                        if (h !== ori_h || w !== ori_w){
                            elf.resize(w, h);
                        }
                    }, 200);
                }
            });
        }
    </script>
    <style type="text/css">
        body {
            height: 100%;
        }
        .div #elfinder {
            height: 100%;
        }
    </style>
<div id="elfinder"></div>
</body>
</html>
